﻿using CHSystemApi.DataAccess.Entities;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace CHSystemApi.Business.implement
{
    public partial class UserBusiness
    {
        public string CreateJwtPlayload(User user, Permission[] permissions)
        {
            IEnumerable<Claim> claims = new Claim[]
            {
                new Claim("uid",user.id.ToString()),
                new Claim(nameof(user.tel),user.tel),
                new Claim(nameof(user.name),user.name),
                new Claim(nameof(user.last_login_time),user.last_login_time.ToString("yyyy-MM-dd HH:mm:ss")),
                new Claim("permissions",JsonConvert.SerializeObject(permissions))
            };
            var secret = Encoding.UTF8.GetBytes(_configuration["JWT:IssuerSigningKey"]);
            var key = new SymmetricSecurityKey(secret);
            var signcreds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwt = new JwtSecurityToken(issuer: _configuration["JWT:Issuer"], audience: _configuration["JWT:Audience"], claims: claims, notBefore: DateTime.Now, expires: DateTime.Now.AddDays(1), signingCredentials: signcreds);
            var JwtHander = new JwtSecurityTokenHandler();
            return JwtHander.WriteToken(jwt);
        }
    }
}
